package com.cloud.util;

import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class DownloadUtil {

    /**
     * @param imageUrl      图片的url
     * @param dirName       本地文件存储文件夹
     * @param imageFileName 本地文件存储文件名
     *                      根据图片url下载图片到本地
     */
    public static void downloadImage(String imageUrl, String dirName, String imageFileName) {
        try {
            Connection conn = Jsoup.connect(imageUrl)
                    .referrer(imageUrl)
                    .userAgent(CookieUtil.USER_AGENT);
            downloadImage(conn, dirName, imageFileName);
        } catch (Exception e) {
            System.err.format("DownloadUtil.getEachImage: %s, %s, %s, catch error\n", imageUrl, dirName, imageFileName);
        }
    }

    public static void downloadImage(Connection conn, String dirName, String imageFileName) throws Exception {
        Connection.Response response = conn.execute();
        BufferedInputStream is = response.bodyStream();
        if (!dirName.endsWith(File.separator)) dirName += File.separator;
        File dest = new File(dirName + imageFileName);
        OutputStream os = new FileOutputStream(dest);
        int len = -1;
        int size = 1024;
        byte[] buf = new byte[size];
        while ((len = is.read(buf, 0, size)) != -1) {
            os.write(buf, 0, len);
        }
        os.close();
        is.close();
    }

    public int[] shuffle(int[] old, int n) {
        int[] arr = new int[n * 2];
        int i = 0, j = n;
        for (int k = 0; k < n; k++) {
            arr[k * 2] = old[i++];
            arr[k * 2 + 1] = old[j++];
        }
        return arr;
    }

}
